package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Controls extends Main implements ActionListener, KeyListener{

	public Controls(int[][] matrix) {
		this.matrix = matrix;

		//find size^2 in the matrix (blank tile) to start the listener. 
		for(int i = 0; i < this.matrix.length; i++)
		{
			for(int j = 0; j < this.matrix.length; j++)
			{
				if(this.matrix[i][j] == (int)(Math.pow(this.matrix.length, 2)))
				{
					indexi = i;
					indexj = j;
				}
			}
		}
	}

	/**
	 * Controls work pretty simple, action listener triggers > keylistener. When it's
	 * triggered it verifies if any of the specified keys were used.
	 * The swapping occures simulating that indexi = y and indexj = x; 
	 * 
	 * The logic is swap the n^2 with the desired tile and then store the location of n^2 in memory again.
	 */
	
	public void left() {	
		try {
			int temp = matrix[indexi][indexj];
			matrix[indexi][indexj] = matrix[indexi][indexj - 1];
			matrix[indexi][indexj - 1] = temp;
			indexj -= 1;
		} catch (Exception e) {

		}
	}
	public void right() {	
		try {
			int temp = matrix[indexi][indexj];
			matrix[indexi][indexj] = matrix[indexi][indexj + 1];
			matrix[indexi][indexj + 1] = temp;
			indexj += 1;
		} catch (Exception e) {

		}
	}
	public void up() {	
		try {
			int temp = matrix[indexi][indexj];
			matrix[indexi][indexj] = matrix[indexi - 1][indexj];
			matrix[indexi - 1][indexj] = temp;
			indexi -= 1;
		} catch (Exception e) {

		}
	}
	public void down() {	
		try {
			int temp = matrix[indexi][indexj];
			matrix[indexi][indexj] = matrix[indexi + 1][indexj];
			matrix[indexi + 1][indexj] = temp;
			indexj += 1;
		} catch (Exception e) {

		}
	}


	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
		if(key == KeyEvent.VK_UP);
		up();
		if(key == KeyEvent.VK_DOWN);
		down();
		if(key == KeyEvent.VK_LEFT);
		left();
		if(key == KeyEvent.VK_RIGHT);
		right();

	}

	public int[][] getMatrix() {
		return matrix;
	}

	public void keyReleased(KeyEvent e){}
	public void keyTyped(KeyEvent e){}
	public void actionPerformed(ActionEvent e){}

	private int[][] matrix;	
	private int indexi;
	private int indexj;

}
